package handler

import (
	"net/http"
	"sync"

	"octopus/internal/domain/interfaces"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var (
	clientsMu sync.RWMutex
	clients   = make(map[*websocket.Conn]struct{})
	upgrader  = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool { return true }, // 生产环境请加强安全校验
	}
)

// RegisterWSClient 注册 WebSocket 客户端
func RegisterWSClient(conn *websocket.Conn) {
	clientsMu.Lock()
	defer clientsMu.Unlock()
	clients[conn] = struct{}{}
}

// UnregisterWSClient 注销 WebSocket 客户端
func UnregisterWSClient(conn *websocket.Conn) {
	clientsMu.Lock()
	defer clientsMu.Unlock()
	delete(clients, conn)
	conn.Close()
}

// broadcast 向所有 WebSocket 客户端推送消息
func broadcast(msg interface{}) {
	clientsMu.RLock()
	defer clientsMu.RUnlock()
	for conn := range clients {
		_ = conn.WriteJSON(msg) // 可加错误处理和断开处理
	}
}

// WebSocketHandler gin 路由处理函数
func WebSocketHandler(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	RegisterWSClient(conn)
	defer UnregisterWSClient(conn)

	// 可选：循环读取客户端消息（如需心跳或客户端主动断开）
	for {
		if _, _, err := conn.NextReader(); err != nil {
			break
		}
	}
}

// NewWebSocketEventHandler 创建一个新的事件处理程序
func NewWebSocketEventHandler() interfaces.EventBus {
	return &webSocketEventBus{}
}

type webSocketEventBus struct{}

func (e *webSocketEventBus) Publish(event interfaces.TaskEvent, payload interface{}) {
	broadcast(gin.H{
		"event": event,
		"data":  payload,
	})
}

func (e *webSocketEventBus) Subscribe(event interfaces.TaskEvent, handler func(interface{})) error {
	// 对于WebSocket，我们只支持发布事件，不支持订阅
	return nil
}